/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.com.seguridad;

import co.com.entidad.TblUsuario;
import co.com.session.TblUsuarioFacade;
import java.awt.event.ActionEvent;
import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import co.com.utilidades.JsfUtil;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.http.HttpSession;

/**
 *
 * @author user
 */
@ManagedBean(name = "Login")
@SessionScoped
public class Login {

    private String username;
    @EJB
    private TblUsuarioFacade ejbUsuarioFacade;
    private String password;
    private boolean logeado = false;
    private boolean esOperador;

    public boolean isEsOperador() {
        return esOperador;
    }

    private long perfil;
    private String compania;

   

    public String getUsername() {
        return username;
    }

    public boolean estaLogeado() {
        return logeado;
    }

    public String getCompania() {
        return compania;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    
    
    public void loginUsuario() {

        List<TblUsuario> listaUsuario = ejbUsuarioFacade.login(username, password);
        RequestContext context = RequestContext.getCurrentInstance();
        
        if (!listaUsuario.isEmpty()) {

            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Propiedades").getString("login"));
            logeado = true;
            compania = listaUsuario.get(0).getCodCompania().getCodCompania();
            perfil = listaUsuario.get(0).getCodRol().getCodRol();

        } else {

            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/1Propiedades").getString("error"));
            logeado = false;

        }
        context.addCallbackParam("estaLogeado", logeado);
        if (logeado) {
            if(perfil ==0){
            context.addCallbackParam("view", "menuAplicacion.xhtml");
            esOperador = true;
            }else{
            context.addCallbackParam("view", "menuAplicacionCompania.xhtml");
            esOperador = false;
            }
        }
       
    }
 
    public void logout() {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
                .getExternalContext().getSession(false);
        session.invalidate();
        logeado = false;

    }

}